package com.qianbei.user;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.ext.HttpCallback;
import com.android.volley.ext.RequestInfo;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.qianbei.R;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.BaseApplication;
import com.qianbei.common.init.GlobalConfig;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.Constant;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerControl.ServerListener;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.utilis.Permission;
import com.qianbei.common.utilis.img.CanmlTools;
import com.qianbei.common.utilis.img.CanmlTools.CamerCallback;
import com.qianbei.user.model.UserMode;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class ChangeUserActivity extends BaseActivity implements CamerCallback {

	private EditText mNameEdit, mCountryEdit, mCityEdit,mIntroduceEdit,mIdentityEdit;

	private ImageView perceter_icon;

	private TextView mCommitBtn;

	private String sexString = "1";// 1男 0女

	private CanmlTools canmlTools = null;

	private String imgData;
	private RequestQueue mQueue;
	private ProgressDialog mDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mQueue = Volley.newRequestQueue(BaseApplication.mApplication);
		setContentView(R.layout.user_change_activity);

		mNameEdit = (EditText) findViewById(R.id.et_name);
		mCityEdit = (EditText) findViewById(R.id.et_city2);
		mCountryEdit = (EditText) findViewById(R.id.country);
		mIntroduceEdit = (EditText) findViewById(R.id.et_introduce);
		mIdentityEdit = (EditText) findViewById(R.id.et_touxie);
		perceter_icon = (ImageView) findViewById(R.id.perceter_icon);
		perceter_icon.setOnClickListener(this);
		mCommitBtn = (TextView) findViewById(R.id.commit_btn);
		mCommitBtn.setOnClickListener(this);

		setTitle("编辑个人资料");

		Register1();
		canmlTools = new CanmlTools(mContext, this);
		mDialog = new ProgressDialog(this);

	}

	private void Register1() {
		ServerControl sc = new ServerControl(Method.GET, URL
				+ "transaction_app/users/user_info?");
		sc.serverListener = new ServerListener() {

			@Override
			public void serverFinish(ServerResult sr) {
				if (isFinishing()){
					return;
				}

				if (sr.isContinue) {
					UserMode mode = JSON.parseObject(
							sr.bodyData.optJSONObject("userInfo").toString(),
							UserMode.class);
					mNameEdit.setText(mode.name);
					mIdentityEdit.setText(mode.identity);

					Glide.with(mContext)
								.load(Constant.URL + mode.profile_image_url)
								.placeholder(R.drawable.ic_launcher)
								.into(perceter_icon);

					mCityEdit.setText(mode.city);
					mCountryEdit.setText(mode.country);
					
					mIntroduceEdit.setText(mode.career);
				}
			}
		};
		new ProgressDialog(mContext).startControl(sc);

	}


	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.btn_login:

			hideSoftInputFromWindow();
			// Util.hideSoftInputFromWindow(v);
			//

			UserMode bean = new UserMode();
			bean.name = mNameEdit.getText().toString();
			bean.career = mIntroduceEdit.getText().toString();
			bean.identity = mIdentityEdit.getText().toString();
			bean.city = mCityEdit.getText().toString();
//			bean.emaiString = email.getText().toString();
			bean.country = mCountryEdit.getText().toString();

			// improvmentData("", name.getText().toString(), sexString,
			// et_introduce.getText().toString(), country.getText()
			// .toString(), et_city2.getText().toString(), "");
			// }
			break;

		case R.id.perceter_icon:
			// startActivity(Login_regist_activity.class);
			checkPermission(v);
			break;
		case R.id.commit_btn:
			commitInfoRequest();
			break;

		default:
			break;
		}
	}


	/**
	 *
	 * android 6.0运行时权限检查
	 *
	 * @param v
     */
	public void checkPermission(View v){
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
			if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
					|| ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
				ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
								Manifest.permission.CAMERA},
						Permission.WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
			}else{
				canmlTools.showCanmel(v.getId(), 2);
			}

		}else {
			canmlTools.showCanmel(v.getId(), 2);
		}

	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);

		if (requestCode == Permission.WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
			if(grantResults.length > 0){

				if (grantResults.length > 1){
					if (grantResults[0] == PackageManager.PERMISSION_GRANTED &&
							grantResults[1] == PackageManager.PERMISSION_GRANTED){
						canmlTools.showCanmel(R.id.perceter_icon, 2);
					}
				}
			}
		}
	}

	/**
	 * 提交用户资料
	 */
	private void commitInfoRequest() {
		final String realName = mNameEdit.getText().toString().trim();
		String country = mCountryEdit.getText().toString().trim();
		String city = mCityEdit.getText().toString().trim();
		String identity = mIdentityEdit.getText().toString().trim();
		String career = mIntroduceEdit.getText().toString().trim();

		if(TextUtils.isEmpty(realName)){
			new MsgAlert().show(getString(R.string.empty_name));
			return;
		}

		if(realName.length() < 2 || realName.length() > 20){
			new MsgAlert().show(getString(R.string.name_length));
			return;
		}

		if(TextUtils.isEmpty(country)){
			new MsgAlert().show(getString(R.string.empty_country));
			return;
		}

		if(TextUtils.isEmpty(city)){
			new MsgAlert().show(getString(R.string.empty_city));
			return;
		}

		if(TextUtils.isEmpty(identity)){
			new MsgAlert().show(getString(R.string.empty_post));
			return;
		}

		if(identity.length() < 2 || identity.length() > 20){
			new MsgAlert().show(getString(R.string.post_length));
			return;
		}

		if(TextUtils.isEmpty(career)){
			new MsgAlert().show(getString(R.string.empty_introduction));
			return;
		}

		if(career.length() < 50 || career.length() > 2000){
			new MsgAlert().show(getString(R.string.introduction_length));
			return;
		}



		Map<String, Object> params = new HashMap<String, Object>();
		params.put("user[name]", realName);
		params.put("user[identity]",identity);
		params.put("user[career]",career);
		params.put("user[country]", country);
		params.put("user[city]", city);
		
		if (!TextUtils.isEmpty(imgData)) {
			params.put("profile_image_url", new File(imgData));
		}

		mDialog.showProgress(getString(R.string.commit_request));
		ServerControl sc = new ServerControl();
		RequestInfo requestInfo = new RequestInfo();
		requestInfo.url = updatInfoString;
		requestInfo.putAllParams(params);
		sc.upload(requestInfo, new HttpCallback() {

			@Override
			public void onStart() {

			}

			@Override
			public void onResult(String string) {
				try {

					JSONObject jsonObject = new JSONObject(string);

					if(!"1".equals(GlobalConfig.getInstance().identity)){
						SetData.setFace(jsonObject.optString("face"));
					}else{
						GlobalConfig.getInstance().can_update_info = false;
					}

					new MsgAlert().show(jsonObject.optString("msg"));

					SetData.setUserName(realName);

				} catch (JSONException e) {
					e.printStackTrace();
				}

			}

			@Override
			public void onLoading(long count, long current) {

			}

			@Override
			public void onFinish() {
				mDialog.close();
				setResult(RESULT_OK);
				finish();
			}

			@Override
			public void onError(Exception e) {
				new MsgAlert().show("保存失败！");
				mDialog.close();
			}

			@Override
			public void onCancelled() {
				Log.i("jiao"," onCancelled");
				mDialog.close();
			}
		});
	}

	@Override
	public void camerPickphoto(String imageUri, int i) {
		imgData = imageUri;
		Glide.with(mContext)
				.load(imageUri)
				.placeholder(R.drawable.ic_launcher)
				.into(perceter_icon);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK) {
			return;
		}
		canmlTools.onresult(requestCode, data);
	}

}
